const fs = require('fs');
const axios = require('axios');
const path = require('path');
const cheerio = require('cheerio');
const { minify } = require('html-minifier');
const beautify = require('js-beautify').html;
const html2pug = require('html2pug');


/*
 * 读取 HTML 文件
 */
async function extractSection(htmlContent, params) {
  const { name, url } = params;
  const caseFolder = path.join(__dirname, '../../samples', name);

  // 压缩 HTML 文档
  const minifiedHtml = minify(htmlContent, {
    removeAttributeQuotes: true,
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    removeComments: true,
  });

  // 使用 cheerio 加载 HTML 内容
  const $ = cheerio.load(minifiedHtml);
  // 提取 id 为 page-content 的 div
  const pageContentDiv = $('#page-content');

  // 创建新的 HTML 内容，仅包含 body 和提取的 div
  const newHtmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modified HTML</title>
</head>
<body>
    ${pageContentDiv.html()}
</body>
</html>
`;

  // 格式化 HTML 文档
  const formattedHtml = beautify(newHtmlContent, {
    indent_size: 2,
    space_in_empty_paren: true,
  });

  const { updatedHtml, extractedUrls } = processDom(formattedHtml, params);


  // 保存修改后的 HTML 到新文件
  fs.writeFileSync(`${caseFolder}/index.html`, updatedHtml, 'utf8');
  // 保存原始网址
  fs.writeFileSync(`${caseFolder}/url.txt`, url, 'utf8');

  // 保存修改后的PUG 到新文件
  const html = cheerio.load(updatedHtml);
  const svgSection = html('body');
  const pugContent = html2pug(`${svgSection.html() || '<h1> 内容未找到<h1>'}`);
  fs.writeFileSync(`${caseFolder}/home.pug`, replaceQuotation(pugContent), 'utf8');

  const caseName = caseFolder.split('/')[caseFolder.split('/').length - 1]
  const promises = extractedUrls.map(async (url, index) => {
  });
  await Promise.all(promises);
}

/*
 * 将 style 属性值中的单引号替换为反引号
 */
function replaceQuotation(htmlString) {
  return htmlString.replace(/'/g, '`')
  // .replace(/(https?:\/\/)/g, '/proxy?url=$1');// 增加图片代理
}

/*
  * 处理DOM
  */
function processDom(htmlContent, params) {
  const { name } = params
  const caseFolder = path.join(__dirname, '../../../samples', name);
  const caseName = caseFolder.split('/')[caseFolder.split('/').length - 1]
  const $ = cheerio.load(htmlContent);
  const urls = [];
  let index = 0;

  const REMAINING_DOM_IDS = ['content_bottom_area', 'activity-name', 'meta_content']
  const REMAINING_ATTRS = [
    'class', 'data-fill', 'data-cpy', 'data-copyright', 'name', 'id', 'data-fail', 'data-mpa-powered-by',
    'data-lazy-bgimg', 'powered-by', 'data-wechat', 'label', 'copyright'
  ]

  REMAINING_DOM_IDS.forEach(domId => {
    $(`#${domId}`).remove(); // 删除多余dom
  })

  const IMAGE_FOLDER = 'images'
  const imgFolder = `${caseFolder}/${IMAGE_FOLDER}`
  // 遍历所有元素
  $('*').each((i, element) => {

    // 删除多余属性
    REMAINING_ATTRS.forEach(attr => { $(element).removeAttr(attr); })

    // 检查是否同时存在 data-src 和 src 属性
    if ($(element).attr('data-src') && $(element).attr('src')) {
      const attrVal = $(element).attr('data-src');
      if (!(attrVal.startsWith('http://') || attrVal.startsWith('https://'))) { return; }
      urls.push(attrVal); // 保存原始 URL
      // $(element).attr('src', imgPath);
      $(element).removeAttr('data-src');
      index++;
    }

    // 检查是否同时存在 data-src 和 src 属性
    if ($(element).tagName === 'img') {
      const src = $(element).attr('src');
      if (!(src.startsWith('http://') || src.startsWith('https://'))) { return; }
      $(element).attr('src', imgPath);
      urls.push(src);
      index++;
    }

    // 检查是否有A tag href
    if ($(element).tagName === 'a') {
      const href = $(element).attr('href');
      if (!(href.startsWith('http://') || src.startsWith('https://'))) { return; }
      $(element).attr('href', imgPath);
      urls.push(src);
      index++;
    }

    Object.keys($(element).data()).forEach(attr => {
      // 删除以 data-v- 开头的属性
      if (attr.startsWith('v-')) {
        $(element).removeAttr(`data-${attr}`);
      }
    });

    // 删除所有属性值为空的属性
    Object.keys($(element).attr()).forEach(attr => {
      const attrValue = $(element).attr(attr);
      if (attrValue === '' || attrValue === 'undefined' || attrValue === 'null') {
        $(element).removeAttr(attr);
      }
    });

    // 处理内联样式
    const style = $(element).attr('style'); // 获取内联样式
    if (style) {
      const urlRegex = /url\(['"]?([^'")]+)['"]?\)/g; // 匹配 url()
      let match;

      // 查找所有 url()
    }

  });

  console.log(`\n✅[${name}]下载成功! 请访问: http://localhost:3333/samples/${name}\n`);
  return { updatedHtml: $.html(), extractedUrls: urls };
}

module.exports = {
  extractSection,
};

